package com.smart.wap.app;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.smart.common.entities.ajax.AjaxResult;
import com.smart.common.entities.constant.SmartConstant;
import com.smart.common.entities.core.BaseSearch;
import com.smart.common.entities.core.Page;
import com.smart.manager.finance.entities.enums.PayPlatform;
import com.smart.manager.finance.entities.enums.PaymentScene;
import com.smart.manager.finance.entities.models.FinanceCurrencyTariff;
import com.smart.manager.finance.entities.models.FinanceOrderCoin;
import com.smart.manager.finance.repository.CurrencyTariffRepository;
import com.smart.manager.finance.repository.OrderCoinRepository;
import com.smart.utils.MemberAcl;
import com.smart.utils.MemberStp;
import com.smart.wap.bodys.CreateOrderResult;
import com.smart.wap.bodys.PaymentBody;
import com.smart.wap.service.AliPayHandler;
import com.smart.wap.service.PaymentService;
import com.smart.wap.service.WXPayHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author xiaxuqiu
 * @date 2023/09/11
 */

@Api(tags = "移动端-支付相关")
@RestController
@RequestMapping(SmartConstant.WAP_API_PREFIX + "app/payment")
@RequiredArgsConstructor
@Log4j2
public class PaymentController {

    private final HttpServletRequest servletRequest;
    private final CurrencyTariffRepository tariffRepository;
    private final PaymentService paymentService;
    private final WXPayHandler wxPayHandler;
    private final AliPayHandler aliPayHandler;

    private final OrderCoinRepository orderCoinRepository;

    @PostMapping(value = "getTariffList")
    @ApiOperation(value = "金币价目表")
    @SaCheckLogin(type = MemberStp.TYPE)
    public AjaxResult<List<FinanceCurrencyTariff>> getTariffList() {
        List<FinanceCurrencyTariff> result = tariffRepository.list();
        return AjaxResult.data(result);
    }


    @PostMapping(value = "createOrder")
    @ApiOperation(value = "金币充值下单")
    @SaCheckLogin(type = MemberStp.TYPE)
    public AjaxResult<CreateOrderResult> createOrder(@RequestBody @Validated PaymentBody.CreateOrderBody body) {
        log.warn("body ={}",body);
        body.checkSign();
        Long memberId = MemberAcl.getLoginId();
        FinanceOrderCoin order = paymentService.createCoinOrder(memberId, body);
        String appId = order.getAppId();
        String orderId = order.getOrderId();
        BigDecimal fee = order.getFee();
        String attached = order.getAttached();
        //获取回调地址
        String notifyUrl = getNotifyUrl(order.getPayPlatform(), appId);
        //支付宝订单
        if (order.getPayPlatform().equals(PayPlatform.ALIPAY)) {
            String payStr = aliPayHandler.pushCoinOrderToAlipay(appId, orderId, fee, notifyUrl, attached);
            CreateOrderResult result = new CreateOrderResult().setNeedPay(true).setResult(payStr).setTradeNo(order.getOrderId());
            return AjaxResult.data(result);
        }
        //微信支付创建订单
        Object obj = wxPayHandler.pushCoinOrderToWechat(appId, orderId, fee, notifyUrl, attached);
        CreateOrderResult result = new CreateOrderResult().setNeedPay(true).setResult(obj).setTradeNo(order.getOrderId());
        return AjaxResult.data(result);
    }

    @GetMapping(value = "payDetail/{orderId}")
    @ApiOperation(value = "单个订单支付详情", notes = "支付后查询")
    @SaCheckLogin(type = MemberStp.TYPE)
    public AjaxResult<FinanceOrderCoin> getPayDetail(@PathVariable String orderId) {
        Long memberId = MemberAcl.getLoginId();
        FinanceOrderCoin result = orderCoinRepository.getPayDetail(memberId, orderId);
        return AjaxResult.data(result);
    }


    @GetMapping(value = "payList")
    @ApiOperation(value = "获取支付记录")
    @SaCheckLogin(type = MemberStp.TYPE)
    public AjaxResult<Page<FinanceOrderCoin>> getPayList(@Validated BaseSearch search) {
        Long memberId = MemberAcl.getLoginId();
        Page<FinanceOrderCoin> result = orderCoinRepository.myPageList(memberId, search);
        return AjaxResult.data(result);
    }


    /**
     * 得到通知url
     *
     * @param payPlatform 支付平台
     * @return {@link String}
     */
    private String getNotifyUrl(PayPlatform payPlatform, String appId) {
        String currentUrl = servletRequest.getRequestURL().toString();
        String platformName = payPlatform.name().toLowerCase();
        String scene = PaymentScene.COIN.name().toLowerCase();
        String callbackUri = SmartConstant.OTHER_API_PREFIX + "payment/callback/".concat(platformName).concat("/").concat(appId).concat("/").concat(scene);
        return currentUrl.replace("http://", "https://")
                .replace("/wap/app/payment/createOrder", callbackUri);
    }
}
